package ywu.tools.timesync.ntp;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

/**
 * @author ywu
 */
public class NtpRequest extends NtpDatagram
{

    public NtpRequest()
    {
        originateTimestamp = System.currentTimeMillis();
        mode = 3;
    }

    /**
     * 将此NTP请求编码为二进制字节流.
     * 
     * <pre>
     * 0    1     4     7         15         23         31
     * +----+-----+-----+----------+----------+----------+
     * | LI |  VN | Mode| Statum   | Poll     |Preciscion|
     * +----+-----+-----+----------+----------+----------+
     * |          Root delay(32 bits)                    |
     * ---------------------------------------------------
     * |          Root despersion(32 bits)               |
     * ---------------------------------------------------
     * |          Reference identifier(32 bits)          |
     * ---------------------------------------------------
     * |                                                 |
     * |          Reference timestamp(64 bits)           |
     * ---------------------------------------------------
     * |                                                 |
     * |          Originate timestamp(64 bits)           |
     * ---------------------------------------------------
     * |                                                 |
     * |          Receive timestamp(64 bits)             |
     * ---------------------------------------------------
     * |                                                 |
     * |          Transmit timestamp(64 bits)            |
     * ---------------------------------------------------
     * |                                                 |
     * |                                                 |
     * |          Authenticator timestamp(96 bits)       |
     * ---------------------------------------------------
     * </pre>
     * 
     * @return
     */
    public ByteBuffer toByteBuffer()
    {
        ByteBuffer buf = ByteBuffer.allocate(60);
        buf.order(ByteOrder.BIG_ENDIAN);
    
        byte cur = 0;
        cur |= version << 3;
        cur |= mode;
        buf.put(cur);
        buf.put((byte) 0);
        buf.put((byte) 0);
        buf.put((byte) 0);
        buf.putInt(0);
        buf.putInt(0);
        buf.putInt(0);
        buf.putLong(0);
    
        buf.putLong(toNtpTimestamp(originateTimestamp));
        buf.putLong(0);
        buf.putLong(0);
        buf.putLong(0);
        buf.putInt(0);
        buf.flip();
        return buf;
    }

}
